//
//  KKImageLibrary.m
//  KKImagePickerController
//
//  Created by Mac mini on 16/1/21.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "KKImageLibraryManager.h"

#import "KKImagePickerManager+Tools.h"

@interface KKImageLibraryManager() {
    
    NSMutableArray *_groupItemArray;
    NSMutableArray *_assetItemArray;
    
    ALAssetsLibrary *_kk_assetsLibrary;
}

@end

@implementation KKImageLibraryManager

+ (instancetype)kk_defaultManager {
    
    static KKImageLibraryManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKImageLibraryManager new];
    });
    return manager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _groupItemArray = [NSMutableArray array];
        _assetItemArray = [NSMutableArray array];
    }
    return self;
}

#pragma mark - Private methods

#pragma mark - Public methods
- (void)kk_searchAllGroupsFromLibrary:(KKImageLibraryManagerAllGroupsHandle)handle {
    
    [_groupItemArray removeAllObjects];
    __weak NSMutableArray* weakGroupArray = _groupItemArray;
    
    if (KKDeviceVersion < 8.0) {
        
        _kk_assetsLibrary = [ALAssetsLibrary new];
        __weak ALAssetsLibrary* weakAssetsLibrary = _kk_assetsLibrary;
        ALAssetsLibraryGroupsEnumerationResultsBlock listGroupResultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
            if (group) {
                if ([[group valueForProperty: ALAssetsGroupPropertyType] integerValue] == ALAssetsGroupSavedPhotos) {
                    KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetsGroup: group];
                    [weakGroupArray insertObject: item atIndex: 0];
                }
                else {
                    KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetsGroup: group];
                    [weakGroupArray addObject: item];
                }
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (handle) {
                        handle(weakGroupArray);
                    }
                });
            }
        };
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [weakAssetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: listGroupResultsBlock failureBlock:^(NSError *error) {
                NSLog(@"Group not found!\n");
                
                [KKImagePickerManager kk_showErrorMessage: @"请在设备的\"设置-隐私-照片\"中允许访问相册权限"];
            }];
        });
    }
    else {
        // 获取相机相册
        {
            PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
            NSInteger count = smartAlbums.count;
            for (NSInteger index = 0; index < count; index++) {
                PHAssetCollection *assetCollection = [smartAlbums objectAtIndex: index];
                PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
                if (assets.count == 0) {
                    break;
                }
                KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
                [weakGroupArray insertObject: item atIndex: 0];
            }
        }
        
        {
            //  用户创建的相册
            PHFetchResult *userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
            NSInteger count = userCollections.count;
            for (NSInteger index = 0; index < count; index++) {
                PHAssetCollection *assetCollection = [userCollections objectAtIndex: index];
                PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
                if (assets.count == 0) {
                    break;
                }
                KKImageLibraryGroupItem *item = [[KKImageLibraryGroupItem alloc] initWithAssetCollection: assetCollection withItemCounts: assets.count];
                [weakGroupArray addObject: item];
            }
        }
        
        if (handle) {
            handle(weakGroupArray);
        }
        
        // 获取所有资源的集合，并按资源的创建时间排序
//        PHFetchOptions *options = [[PHFetchOptions alloc] init];
//        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
//        {
//            PHFetchResult *momentRes = [PHAssetCollection fetchMomentsWithOptions:options];
//            NSLog(@"momentRes = %@", momentRes);
//        }
        
//        options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        
//        PHFetchResult *assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
//        NSLog(@"assetsFetchResults = %@", assetsFetchResults);
//        // 在资源的集合中获取第一个集合，并获取其中的图片
//        PHCachingImageManager *imageManager = [[PHCachingImageManager alloc] init];
//        PHAsset *asset = assetsFetchResults[0];
//        [imageManager requestImageForAsset:asset
//                                targetSize: CGSizeMake(100, 100)
//                               contentMode:PHImageContentModeAspectFill
//                                   options:nil
//                             resultHandler:^(UIImage *result, NSDictionary *info) {
//                                 
//                                 // 得到一张 UIImage，展示到界面上
//                                 NSLog(@"result = %@", result);
//                             }];
    }
}

//  获取相册中的相片集
- (void)kk_searchAllItemsFromLibraryWithGroup:(id)group result:(KKImageLibraryManagerAllItemsOfGroupHandle)handle {
    
    [_assetItemArray removeAllObjects];
    __weak NSMutableArray* weakAssetItems = _assetItemArray;
    
    if (KKDeviceVersion < 8.0){
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if (result) {
                    KKImageItem *item = [KKImageItem new];
                    item.asset_7 = result;
                    [weakAssetItems addObject: item];
                }
                else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        if (handle) {
                            handle(weakAssetItems);
                        }
                    });
                }
            }];
        });
    }
    else {
        PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:group options:nil];
        for (PHAsset *asset in assets) {
            KKImageItem *item = [KKImageItem new];
            item.asset_8 = asset;
            [weakAssetItems addObject: item];
        }
        if (handle) {
            handle(weakAssetItems);
        }
    }
}

@end



@implementation KKImageLibraryGroupItem

- (UIImage *)kk_posterImage {
    if (_kk_posterImage == nil) {
        _kk_posterImage = [UIImage imageWithCGImage: _kk_assetsGroup.posterImage];
    }
    return _kk_posterImage;
}

- (NSInteger)kk_count {
    if (_kk_count == 0) {
        _kk_count = _kk_assetsGroup.numberOfAssets;
    }
    return _kk_count;
}

- (NSString *)kk_groupName {
    if (_kk_groupName == nil) {
        _kk_groupName = [_kk_assetsGroup valueForProperty: ALAssetsGroupPropertyName];
    }
    return _kk_groupName;
}

- (instancetype)initWithAssetsGroup:(ALAssetsGroup *)assetsGroup {
    self = [super init];
    if (self) {
        _kk_assetsGroup = assetsGroup;
    }
    return self;
}


- (instancetype)initWithAssetCollection:(PHAssetCollection *)assetCollection withItemCounts:(NSInteger)counts {
    self = [super init];
    if (self) {
        _kk_assetCollection = assetCollection;
        _kk_groupName = _kk_assetCollection.localizedTitle;
        _kk_count = counts;
    }
    return self;
}

@end

@implementation KKImageItem
@end
